<?php

/**
 * 第三方（公司其他项目数据接口）
 */

namespace Api\Controller;

use Common\Controller\BaseController;
use Think\Crypt\Driver\Xxtea;

class ThirdController extends BaseController {

    public function _initialize() {
        
    }

    /**
     * 上传头像接口
     * @param string $token 加密验证
     * @param $_File $phone 图片文件信息
     * @return string 图片路径
     */
    public function uploadFace() {
        $token = I('token');
        $oXxtea = new Xxtea();
        $iUserId = $oXxtea->decrypt(base64_decode($token), C('XXTEA_KEY'));
        $path = $this->uploadfile('photo', 'Account', 1024 * 1024 * 2);
        $this->returnList($path);
    }

    /**
     * 授权开通帐号权限（CRM执行授权）
     * @param   int customer_id 客户ID
     * @param   string phone 客户电话
     * @param   string   company_name 企业名称
     * @param   string start_time   服务期开始时间
     * @param   string end_time     服务器结束时间
     * @return 
     */
    public function pushService() {
        $sign = I('sign');
        $arrData = $_POST;
        unset($arrData['sign']);
        $checkSign = md5(http_build_query(ksort($arrData)) . C('XXTEA_KEY'));
        if ($checkSign != $sign) {
            $this->error('认证失败');
        }
        //授权数据-添加
        $Company = M('Company');
        $companyInfo = $Company->where(array('custmer_id' => $arrData['custmer_id']))->find();
//        $user_id = $Company->where(array('custmer_id' => $arrData['custmer_id']))->getField('user_id');
//        if (!empty($user_id)) {
//            $this->error('该客户已绑定');
//        }
        $user_id = $this->quickRegister($arrData['phone']);
        list($company_status, $user_status_is_change) = $this->checkingSevertime($arrData['start_time'], $arrData['end_time']);     //根据企业服务器判断企业状态
        //企业创建或更新
        $companyData = array(
            'custmer_id' => $arrData['custmer_id'],
            'company_name' => $arrData['company_name'],
            'base_num' => 20,
            'sever_start_time' => $arrData['start_time'],
            'sever_stop_time' => $arrData['end_time'],
            'status' => $company_status
        );


        if (!empty($companyInfo)) {
            $res = $Company->where(array('user_id' => $user_id))->save($companyData);
            if ($user_status_is_change === true) {    //企业过期，成员也过期
                //更新企业中成员状态,将【使用中】改为【已过期】
                M('user_company_relat')->where(array('company_id' => $companyInfo['company_id'], 'status' => 1))->save(array('status' => 2));
            }
        } else {
            $companyData['user_id'] = $user_id;
            $companyData['create_time'] = date('Y-m-d H:i:s');
            $Company->add($companyData);
        }
    }

    /**
     * 快速注册
     * @param str phone 注册账号
     * @return int user_id 注册用户ID
     */
    private function quickRegister($phone) {
        $User = M('User');
        $userInfo = $User->field('user_id')->where(array('phone' => $phone))->find();
        if (empty($userInfo)) {
            $strRand = mt_rand(111111, 999999);
            $userData['phone'] = $arrData['phone'];
            $userData['password'] = md5($strRand);
            $userData['create_time'] = date('Y-m-d H:i:s');
            $userData['type'] = 1;  //账号所属平台：1-企业培训，2-菁英汇；（二进行制位运算）
            $user_id = $User->add($userData);
            $SMS_TPL = C('SMS_TPL');
            $sms_cont = str_replace(array('%phone%', '%code%'), array($arrData['phone'], $strRand), $SMS_TPL[2]);
            //sys_sms($arrData['phone'], $sms_cont);
        } else {
            //开启type权限（位运算）
            $User->where(array('user_id' => $userInfo['user_id']))->setField('type', array('exp', "type|1"));
            $user_id = $userInfo['user_id'];
        }
        return $user_id;
    }

    /**
     * 判断企业状态
     * company_status 企业状态变为：
     * 0-待生效：成员状态不变
     * 1-使用中：成员状态不变
     * 2-已过期：成员状态变为已过期（qy_user_company_relat.status=2）
     * @param string $startTime
     * @param string $endtime
     * @return array company_status int 该企业的状态； user_status_is_change boole 用户的状态是否发生变化
     */
    private function checkingSevertime($startTime, $endtime) {
        $nowDate = date("Y-m-d H:i:s");
        if ($startTime > $nowDate) {
            $arrStatus = array('company_status' => 0, 'user_status_is_change' => false);
        } elseif ($startTime <= $nowDate && $endtime >= $nowDate) {
            $arrStatus = array('company_status' => 1, 'user_status_is_change' => false);
        } elseif ($endtime < $nowDate) {
            $arrStatus = array('company_status' => 2, 'user_status_is_change' => true);
        }
        return $arrStatus;
    }

    /**
     * 临时菁英汇调用
     */
    public function jyh_send() {
        $phone = $_POST['phone'];
        $content = $_POST['content'];
        sys_sms($phone, $content);
    }

}
